package org.ruixue.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

    /**
     * post方式发送请求
     */
    public static String sendByPostJson(String url, String params) throws Exception {
        String retStr = "";
        if (StringUtils.isNotEmpty(url) && params != null) {
            // 创建url
            URL urlObj = new URL(url);
            // 打开http连接
            HttpURLConnection httpConn = (HttpURLConnection) (urlObj.openConnection());
            // 设置http连接属性
            httpConn.setRequestProperty("Content-Type", "application/json");
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            // 发送请求数据,并设置为utf-8编码
            OutputStream out = httpConn.getOutputStream();
            out.write(params.getBytes("UTF-8"));
            out.close();
            // 接受响应数据
            InputStream isr = httpConn.getInputStream();
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            int b;
            while ((b = isr.read()) != -1) {
                bao.write(b);
            }
            isr.close();
            // 关闭http连接
            httpConn.disconnect();
            // 返回响应数据,并设置为utf-8编码
            retStr = new String(bao.toByteArray(), "ISO-8859-1");
            retStr = new String(retStr.getBytes("ISO-8859-1"), "UTF-8");
        }
        return retStr;
    }

}
